package com.ray.interceptor.base;

import com.ray.util.Commen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BizInterceptConfig {

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${rayboot.interceptor}")
    private String baseInterceptor;

    public <T> T initIntercept(String bizIntercept) throws Exception {
        if (!Commen.isEmptyy(bizIntercept)) {
            try {
                // 实例化自定义拦截
                return (T) applicationContext.getAutowireCapableBeanFactory().createBean(Class.forName(bizIntercept));
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("实例化拦截器异常，请检测类是否存在：" + bizIntercept);
            }
        }
        return null;
    }

    public <T> T initMetaObjectIntercept(String bizIntercept) throws Exception {
        Object o = initIntercept(bizIntercept);
        if (o == null) {
            // 命中默认拦截
            return (T) applicationContext.getAutowireCapableBeanFactory().createBean(Class.forName(baseInterceptor));
        }
        return (T) o;
    }
}
